<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .slider-bar {
            position: absolute;
            left: 50%;
            top: 300px;
            margin-left: 600px;
            width: 45px;
            height: 130px;
            background-color: pink;
        }
        
        .w {
            width: 1200px;
            margin: 10px auto;
        }
        
        .header {
            height: 150px;
            background-color: purple;
        }
        
        .banner {
            height: 250px;
            background-color: skyblue;
        }
        
        .main {
            height: 3000px;
            background-color: yellowgreen;
        }
        
        span {
            display: none;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>

<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主体部分</div>

    <script>
        var slider = document.querySelector('.slider-bar')
        var header = document.querySelector('.header')
        var banner = document.querySelector('.banner')
        var main = document.querySelector('.main')
        var bannerTop = banner.offsetTop
        var slideTop = slider.offsetTop - bannerTop
        var goBack = document.querySelector('.goBack')
        var mainTop = main.offsetTop
            // 页面滚动事件
        document.addEventListener('scroll', function() {
            // console.log(banner.offsetTop);
            // 当页面滚动到banner盒子,slide-bar改为固定定位
            if (window.pageYOffset >= bannerTop) {
                slider.style.position = 'fixed'
                slider.style.top = slideTop + 'px'
            } else {
                slider.style.position = 'absolute'
                slider.style.top = '300px'
            }
            // 当页面滚动到main盒子,就显示返回盒子
            if (window.pageYOffset >= mainTop) {
                goBack.style.display = 'block'
            } else {
                goBack.style.display = 'none'
            }

        })
    </script>
</body>

</html>